package com.sixeco.apigetway;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sixeco.apigetway.common.CommonIO;
import com.sixeco.apigetway.common.CommonVar;
import com.sixeco.apigetway.handle.ChannelHandleInit;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Http-Getway启动类
 * 
 * @author tianzhenjiu
 *
 */
public class GetWayServer {

	static Logger logger = LoggerFactory.getLogger(GetWayServer.class);

	String params[] = { "-dh", "-dp", "-sh", "-sp","-sl","-sf" };

	public void start(String bindHost,int port) {

		NioEventLoopGroup LoopGroup = new NioEventLoopGroup(2);
		NioEventLoopGroup childrenGroup=CommonVar.Proxy.httpgroup;

		try {
			ServerBootstrap bootstrap = new ServerBootstrap();

			bootstrap.group(LoopGroup, childrenGroup);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.childHandler(new ChannelHandleInit());

			ChannelFuture channelFuture = bootstrap.bind(bindHost,port);
			channelFuture.addListener((listener) -> {

				if (!listener.isSuccess()) {
					logger.warn("启动失败", listener.cause());
					throw new RuntimeException(listener.cause());

				}else {
					logger.info("启动成功地址{},端口{}",bindHost,port );
				}
				});
		} catch (Exception e) {
			LoopGroup.shutdownGracefully();
			childrenGroup.shutdownGracefully();
		}

	}

	public Map<String, String> initArgs(String[] args) {

		
		 Map<String, String>  paramsMap=new HashMap<>();
		if (args != null) {

			for (int i = 0; i < args.length; i++) {
				for (int j = 0; j < params.length; j++) {
						if(args[i].startsWith(params[j])) {
							String key=args[i].substring(1,3);
							String value=args[i].substring(3);
							paramsMap.put(key, value);
						}
				}
			}
		}
		
		
		
		paramsMap.putIfAbsent("sh", "0.0.0.0");
		paramsMap.putIfAbsent("sp", "80");
		paramsMap.putIfAbsent("sl", "false");
		
		return paramsMap;
	}

	public static void main(String[] args) {

		
		GetWayServer getWayServer=new GetWayServer();
		
		Map<String, String>  paramsMap=getWayServer.initArgs(args);
		 
		String myhost=paramsMap.get("sh") ;
		int myport=Integer.valueOf(paramsMap.get("sp"));
		
	
		

		
		boolean isssl=Boolean.valueOf(paramsMap.get("sl"));

		String sf=null;
		if(isssl) {
			sf=paramsMap.get("sf");
			CommonVar.HttpChunk.SSL_ISENABLE=true;
			CommonVar.HttpChunk.SSL_JKSPATH=sf;
			
		}
		
		
		String proxyHosts=paramsMap.get("dh") ;
		String proxyPorts=paramsMap.get("dp");
		
		
		StringTokenizer stringTokenizerHost=new StringTokenizer(proxyHosts, ",");
		StringTokenizer stringTokenizerPort=new StringTokenizer(proxyPorts, ",");
		
		List<SocketAddress> socketAddresses=new LinkedList<>();
		while(stringTokenizerHost.hasMoreElements()
			&&stringTokenizerPort.hasMoreElements()) {
			
		
			try {
				
				String host=String.valueOf(stringTokenizerHost.nextElement());
				int port=Integer.valueOf(String.valueOf(stringTokenizerPort.nextElement()));
				socketAddresses.add(new InetSocketAddress(host, port));
			} catch (Exception e) {
				logger.warn("解析socket地址异常",e);
			}
		}
		
	
		CommonVar.Proxy.proxySockets=socketAddresses;
		CommonIO.getInstance();
		
		
		getWayServer.start(myhost, myport);
	}

}
